package lambda;

import lambda.bean.Multi;
import lambda.bean.Single;
import lambda.bean.User;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.function.*;

public class LambdaDemo {
    static List<Integer> intData = Arrays.asList(5,4,3,2,1);

    public static void lambdaTest() {
        // 旧写法
        intData.sort(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o1 - o2;
            }
        });

        // Lambda
        intData.sort((o1, o2) -> o1 - o2);

        // 多条处理语句，需要大括号
        Thread thread = new Thread(() -> {
            String test = "hello";
            System.out.println(test);
        });
    }

    public static void methodReferencesTest() {
        // 对象::实例方法, 将lambda的参数当做方法的参数使用
        Consumer<String> sc = System.out::println;
        // 等效
        Consumer<String> sc2 = (x) -> System.out.println(x);
        Consumer<String> sc3 = new Consumer<String>() {
            @Override
            public void accept(String s) {
                System.out.println(s);
            }
        };
        sc.accept("618, 狂欢happy");

        // 类::静态方法
        Function<Integer, String> sf = String::valueOf;
        //等效
        Function<Integer, String> sf2 = new Function<Integer, String>() {
            @Override
            public String apply(Integer integer) {
                return String.valueOf(integer);
            }
        };
        System.out.println(sf.apply(888));

        // 类::实例方法  将lambda的第一个参数当做方法的调用者，其他的参数作为方法的参数, 难理解，不推荐
        BiPredicate<String, String> sbp = String::equals;
        // 等效
        BiPredicate<String, String> sbp2 = new BiPredicate<String, String>() {
            @Override
            public boolean test(String s, String s2) {
                return s.equals(s2);
            }
        };
        boolean test = sbp.test("a", "A");

        // 无参的构造方法就是类::实例方法模型
        Supplier<User> us = User::new;
        // 等效
        Supplier<User> us2 = () -> new User();
        //获取对象
        User user = us.get();
        Function<String, User> uf = User::new;
        Function<String, User> uf2 = id -> new User(id);
    }

    public static void main(String[] args) {

    }
}
